package com.hanhai.material.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.*;
import com.hanhai.material.device.service.*;
import com.hanhai.material.device.utils.kingdee.AsyncTask;
import com.hanhai.material.device.utils.kingdee.KingdeeUtils;
import com.hanhai.material.utils.AutoGetDataUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.hanhai.material.device.entity.table.SysBadRecordTableDef.SYS_BAD_RECORD;
import static com.hanhai.material.device.entity.table.SysMachinePlcTableDef.SYS_MACHINE_PLC;
import static com.hanhai.material.device.entity.table.SysPlcTableDef.SYS_PLC;
import static com.hanhai.material.device.entity.table.SysProductRecordShiftTableDef.SYS_PRODUCT_RECORD_SHIFT;
import static com.hanhai.material.device.entity.table.SysProductRecordTableDef.SYS_PRODUCT_RECORD;
import static com.hanhai.material.device.entity.table.SysWorkPlanTableDef.SYS_WORK_PLAN;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.*;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2023/10/18 11:26:03
 */
@RestController
@RequestMapping("/product_record")
@Log4j2
public class SysProductRecordController {

    @Autowired
    private SysProductRecordService sysProductRecordService;

    @Autowired
    private SysWorkPlanService sysWorkPlanService;

    @Autowired
    AutoGetDataUtils autoGetDataUtils;

    @Autowired
    SysMachinePlcService sysMachinePlcService;

    /**
     * 添加。
     *
     * @param sysProductRecord
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody SysProductRecord sysProductRecord) {
        log.error("ProductRecord：{}", JSONObject.toJSONString(sysProductRecord));
        LocalDate date = sysProductRecord.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = LocalDateTime.of(date.getYear(), date.getMonthValue(), date.getDayOfMonth(), now.getHour(), now.getMinute());
        Date productDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Date nowDate = new Date();
        String id = fromDateToString("yyyyMMddHHmm", nowDate) + sysProductRecord.getMachineName() + sysProductRecord.getWorkPlanId();
        sysProductRecord.setId(id);
        sysProductRecord.setNormal(true);
        String workPlanId = sysProductRecord.getWorkPlanId();
        QueryWrapper queryWrapper = QueryWrapper.create();
//        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(workPlanId));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.MOLD_SAME.eq(false));
        queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));

        if(now.getHour()<8){
            now= now.minusDays(1);
            sysProductRecord.setProductDate(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        }
        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.list(queryWrapper);
        List<SysProductRecord> sysProductRecordList1 = new ArrayList<>();
        if (sysProductRecordList.isEmpty()) {
            queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(workPlanId));
            queryWrapper.select(sum(SYS_PRODUCT_RECORD.TOTAL_COUNT).as("total_count"));
            queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));
            SysProductRecord productRecord1 = this.sysProductRecordService.getOne(queryWrapper);
            int sum = 0;
            if (productRecord1 != null) {
                sum = productRecord1.getTotalCount();
            }
            sysProductRecord.setNowProductNum(sum);
            sysProductRecord.setContinue(true);
            sysProductRecord.setOver(false);
            sysProductRecord.setGoodNum(sum);
            sysProductRecord.setStart(true);
            sysProductRecord.setNormal(true);
            sysProductRecord.setActualStartTime(new Date());
            sysProductRecord.setTotalCount(sum);
            LocalDateTime localDate2 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 20, 0, 0);
            LocalDateTime localDate1 = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 8, 0, 0);
            if (now.isAfter(localDate2) && now.isBefore(localDate1)) {
                sysProductRecord.setShift("夜班");
            } else {
                sysProductRecord.setShift("白班");
            }
            SysWorkPlan workPlan = this.sysWorkPlanService.getById(workPlanId);

            if (workPlan != null) {
                sysProductRecord.setProductId(workPlan.getProductId());
                sysProductRecord.setProductName(workPlan.getProductName());
                sysProductRecord.setShortName(workPlan.getShortName());
                try {
                    sysProductRecord.setPaperBoxNumber(workPlan.getPaperBoxNumber().intValue());
                } catch (Exception e) {
                    sysProductRecord.setPaperBoxNumber(1);
                }
                sysProductRecord.setExchangeType(workPlan.getExchangeType());
                sysProductRecord.setMoldSame(workPlan.isMoldSame());
                if (workPlan.getProductNum() != null) {
                    sysProductRecord.setWorkPlanProductNum(workPlan.getProductNum());
                }
                sysProductRecord.setMoldSame(workPlan.isMoldSame());
                sysProductRecord.setExchangeType(workPlan.getExchangeType());
                sysProductRecord.setBadNum(0);
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
                SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                if (sysMachinePlc != null) {
                    sysProductRecord = this.autoGetDataUtils.getWeightDataStart(sysMachinePlc, sysProductRecord);
                    sysProductRecord.setHasWeight(sysMachinePlc.isHasWeight());
                    sysProductRecord.setTwoWeight(sysMachinePlc.isHasTwoWeight());
                } else {
                    sysProductRecord.setTwoWeight(false);
                    sysProductRecord.setHasWeight(false);
                }
                sysProductRecord.setAuto(false);
                sysProductRecord.setId(UUID.randomUUID().toString());
                boolean result = this.sysProductRecordService.save(sysProductRecord);
                log.error("SYsProductRecordL:{}", JSONObject.toJSONString(sysProductRecord));
                if (result) {
                    sysProductRecordList1.add(0, sysProductRecord);
                    if (workPlan.isMoldSame()) {
                        SysProductRecord sysProductRecord1 = startTwo(workPlan, sysProductRecord);
                        log.error("SysProductRecord1:{}", sysProductRecord1);
                    }
                }
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
                queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull());
                queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull());
                queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));
                List<SysProductRecord> productRecordList = this.sysProductRecordService.list(queryWrapper);

                return ResultTool.success(productRecordList);
            }


        }

        return ResultTool.fail("该机台已有工单正在生产");


    }

    public SysProductRecord startTwo(SysWorkPlan sysWorkPlan, SysProductRecord sysProductRecord) {
        log.error("两个:{},工单：{}", sysProductRecord, sysWorkPlan);
        SysProductRecord sysProductRecord1 = new SysProductRecord();
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(sysWorkPlan.getPlanStartTime()));
        queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.ne(sysWorkPlan.getWorkPlanId()));
        queryWrapper.where(SYS_WORK_PLAN.MOLD_SAME.eq(true));
        queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
        log.error("SQL:{}", queryWrapper.toSQL());
//        SysWorkPlan sysWorkPlan1 = this.sysWorkPlanService.getOne(queryWrapper);
        List<SysWorkPlan> workPlanList=this.sysWorkPlanService.list(queryWrapper);
        for(SysWorkPlan sysWorkPlan1 : workPlanList){
            String workPlanId = sysWorkPlan1.getWorkPlanId();
            sysProductRecord1.setWorkPlanId(workPlanId);

            Date productDate = sysProductRecord.getProductDate();
            Date nowDate = new Date();
            log.error("SysWOrk:{}", sysWorkPlan1);
            queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(sysWorkPlan1.getWorkPlanId()));
            queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
            queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
//                queryWrapper.where(SYS_PRODUCT_RECORD.IS_START.eq(true));
//                queryWrapper.where(SYS_PRODUCT_RECORD.IS_NORMAL.eq(true));
//                queryWrapper.where(SYS_PRODUCT_RECORD.IS_CONTINUE.eq(true));
            List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.list(queryWrapper);
            log.error("SysProductRecord:{},Data:{}", queryWrapper.toSQL(), sysProductRecordList);
            if (sysProductRecordList.isEmpty()) {
                queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(sysWorkPlan1.getWorkPlanId()));
                queryWrapper.select(sum(SYS_PRODUCT_RECORD.TOTAL_COUNT).as("total_count"));
                SysProductRecord productRecord1 = this.sysProductRecordService.getOne(queryWrapper);
                int sum = 0;
                if (productRecord1 != null) {
                    sum = productRecord1.getTotalCount();
                }
                sysProductRecord1 = sysProductRecord;
                sysProductRecord1.setProductDate(productDate);
                sysProductRecord1.setNowProductNum(sum);
                sysProductRecord1.setContinue(true);
                sysProductRecord1.setOver(false);
                sysProductRecord1.setGoodNum(sum);
                sysProductRecord1.setStart(true);
                sysProductRecord1.setNormal(true);
                sysProductRecord1.setWorkPlanId(sysWorkPlan1.getWorkPlanId());
                sysProductRecord1.setActualStartTime(sysProductRecord.getActualStartTime());
                sysProductRecord1.setTotalCount(sum);
                sysProductRecord1.setProductId(sysWorkPlan1.getProductId());
                sysProductRecord1.setProductName(sysWorkPlan1.getProductName());
                sysProductRecord1.setShortName(sysWorkPlan1.getShortName());
                try {
                    sysProductRecord1.setPaperBoxNumber(sysWorkPlan1.getPaperBoxNumber().intValue());
                } catch (Exception e) {
                    sysProductRecord1.setPaperBoxNumber(1);
                }
                sysProductRecord1.setExchangeType(sysWorkPlan1.getExchangeType());
                sysProductRecord1.setMoldSame(sysWorkPlan1.isMoldSame());
                if (sysWorkPlan1.getProductNum() != null) {
                    sysProductRecord1.setWorkPlanProductNum(sysWorkPlan1.getProductNum());
                }
                sysProductRecord1.setMoldSame(sysWorkPlan1.isMoldSame());
                sysProductRecord1.setExchangeType(sysWorkPlan1.getExchangeType());
                sysProductRecord1.setBadNum(0);
                sysProductRecord1.setId(UUID.randomUUID().toString());
                boolean result = this.sysProductRecordService.save(sysProductRecord1);


            }
        }

        return null;
    }

    @PostMapping("/end")
    public Result<?> end(@RequestBody List<SysProductRecord> sysProductRecordList) throws InterruptedException {
        Date date = new Date();
        for (SysProductRecord sysProductRecord : sysProductRecordList) {
            System.out.println("SysPss:" + sysProductRecord.toString());
            sysProductRecord.setContinue(false);
            sysProductRecord.setNormal(false);
            sysProductRecord.setStart(false);
            sysProductRecord.setEntry(true);
            sysProductRecord.setActualEndTime(date);
            if (sysProductRecord.isHasWeight()) {
                QueryWrapper queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_MACHINE_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
                SysMachinePlc sysMachinePlc = this.sysMachinePlcService.getOne(queryWrapper);
                if (sysMachinePlc != null) {
                    sysProductRecord = this.autoGetDataUtils.getWeightDataEnd(sysMachinePlc, sysProductRecord);

                } else {
                    sysProductRecord.setTwoWeight(false);
                    sysProductRecord.setHasWeight(false);
                }
            } else {
                sysProductRecord.setTwoWeight(false);
                sysProductRecord.setHasWeight(false);
            }
        }
        boolean result = sysProductRecordService.updateBatch(sysProductRecordList);
        return result ? ResultTool.success() : ResultTool.fail();
    }


    @Autowired
    AsyncTask asyncTask;

    @PostMapping("/endToChange")
    public Result<?> endToChange(@RequestBody List<SysProductRecord> sysProductRecordList) throws InterruptedException, IOException {
        for (SysProductRecord sysProductRecord : sysProductRecordList) {
            if (sysProductRecord.getTotalCount() > 0) {
                LocalDateTime nowTime = LocalDateTime.now();
                LocalDate nowDate = LocalDate.now();
                LocalDateTime startDateTime = nowDate.atTime(8, 0, 0);
                LocalDateTime endDateTime = nowDate.atTime(20, 0, 0);
                if (nowTime.isAfter(startDateTime) && nowTime.isBefore(endDateTime)) {
                    saveProductLight(sysProductRecord);
                } else {
                    saveProductNight(sysProductRecord);
                }
            }

        }
        Result<?> result = this.asyncTask.exchange3(sysProductRecordList);
//        Result<?> result = ResultTool.success();

//        if (result.getSuccess()) {

        return result;
    }

    @PostMapping("/endToExit")
    public Result<?> endToExit(@RequestBody List<SysProductRecord> sysProductRecordList) throws InterruptedException, IOException {
        for (SysProductRecord sysProductRecord : sysProductRecordList) {
//            if (sysProductRecord.getTotalCount() > 0) {
//            sysProductRecord.setTotalCount(2);
//            sysProductRecord.setBadNum(1);
//            sysProductRecord.setGoodNum(1);
                LocalDateTime nowTime = LocalDateTime.now();
                LocalDate nowDate = LocalDate.now();
                LocalDateTime startDateTime = nowDate.atTime(8, 0, 0);
                LocalDateTime endDateTime = nowDate.atTime(20, 0, 0);
                if (nowTime.isAfter(startDateTime) && nowTime.isBefore(endDateTime)) {
                    saveProductLight(sysProductRecord);
                } else {
                    saveProductNight(sysProductRecord);
                }
            }
//        }
        Result<?> result = this.asyncTask.exchange4(sysProductRecordList);
//        Result<?> result = ResultTool.success();
//        if (result.getSuccess()) {

//        }
        return result;
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return sysProductRecordService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param sysProductRecord
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("update")
    public Result<?> update(@RequestBody SysProductRecord sysProductRecord) throws IOException {
        String id = sysProductRecord.getId();
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD.ID.eq(sysProductRecord.getId()));

        boolean result = this.sysProductRecordService.remove(queryWrapper);
        log.error("SQL:{}", queryWrapper.toSQL());
        if (result) {
            sysProductRecord.setId(UUID.randomUUID().toString());
            result = this.sysProductRecordService.save(sysProductRecord);
            if (result) {
//                queryWrapper=QueryWrapper.create();
//                queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_RECORD_ID.eq(id));
//                List<SysProductRecordShift> productRecordShiftList=this.sysProductRecordShiftService.list(queryWrapper);
//                if(!productRecordShiftList.isEmpty()){
//                    for(SysProductRecordShift productRecordShift:productRecordShiftList){
//                        productRecordShift.setProductRecordId(sysProductRecord.getId());
//                    }
//                    this.sysProductRecordShiftService.updateBatch(productRecordShiftList);
//                }
//
//                queryWrapper=QueryWrapper.create();
//
//                List<SysProductRecordShift> productRecordShiftList=this.sysProductRecordShiftService.list(queryWrapper);
//                if(!productRecordShiftList.isEmpty()){
//                    for(SysProductRecordShift productRecordShift:productRecordShiftList){
//                        productRecordShift.setProductRecordId(sysProductRecord.getId());
//                    }
//                    this.sysProductRecordShiftService.updateBatch(productRecordShiftList);
//                }
                try {
                    this.dataRefresh(sysProductRecord);
                } catch (Exception e) {

                }
                return ResultTool.success();
            } else {
                return ResultTool.fail();
            }

        }
        return ResultTool.fail();
    }

    @Autowired
    SysPlcService sysPlcService;
    @Autowired
    SysBadRecordService sysBadRecordService;

    public SysProductRecord dataRefresh(SysProductRecord sysProductRecord) throws IOException {
        Date startDate = sysProductRecord.getActualStartTime();
        LocalDate localDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime localDateTime = localDate.atTime(8, 0);
        Date endDate = sysProductRecord.getActualEndTime();
        if (endDate == null) {
            endDate = new Date();
        }
        String start = fromDateToString("yyyy-MM-dd HH:mm:ss", startDate);
        String end = fromDateToString("yyyy-MM-dd HH:mm:ss", endDate);

        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PLC.CREATE_TIME.between(start, end));
        queryWrapper.select(max(SYS_PLC.MODE_NUM).subtract(min(SYS_PLC.MODE_NUM)).as("mode_num"))
                .select(SYS_PLC.ID, SYS_PLC.CREATE_TIME, SYS_PLC.MACHINE_NAME);
        log.error("SQL:{}", queryWrapper.toSQL());
        SysPlc sysPlc = this.sysPlcService.getOne(queryWrapper);
        queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysProductRecord.getWorkPlanId()));
        queryWrapper.where(SYS_BAD_RECORD.CREATE_TIME.between(start, end));
        queryWrapper.select(sum(SYS_BAD_RECORD.NUM).as("num"));
        SysBadRecord badRecord = this.sysBadRecordService.getOne(queryWrapper);

        int badNum = 0;
        if (badRecord != null) {
            badNum = badRecord.getNum();
        }
        log.error("PLC:{}", JSONObject.toJSONString(sysPlc));
        log.error("ProductRecord:{}", JSONObject.toJSONString(sysProductRecord));
        if (sysPlc != null) {
            double moldNumber = 1;
            if (sysProductRecord.getWorkPlan() != null) {
                moldNumber = sysProductRecord.getWorkPlan().getMoldNumber();
                if (moldNumber <= 0) {
                    moldNumber = 1;
                }
            }
            sysProductRecord.setBadNum(badNum);
            double nowProductNum = sysPlc.getModeNum() * moldNumber;
            log.error("nowProductNum:{}", nowProductNum);
            int totalCount = 0;
            if (nowProductNum < 0) {
                nowProductNum = 0;
            } else {
                try {
                    totalCount = (int) (nowProductNum + sysProductRecord.getNowProductNum());
                } catch (Exception exception) {
                    totalCount = (int) (nowProductNum);
                }
                log.error("TotalCount:{}", totalCount);
                sysProductRecord.setGoodNum(totalCount - badNum);
                sysProductRecord.setTotalCount(totalCount);
            }
            SysProductRecord productRecord = this.sysProductRecordService.getById(sysProductRecord.getId());
            try {
                if (productRecord.getActualEndTime() == null) {
                    this.sysProductRecordService.updateById(sysProductRecord);
                } else {

                }
            } catch (Exception e) {
                this.sysProductRecordService.updateById(sysProductRecord);

            }
        } else {
            double moldNumber = 1;
            if (sysProductRecord.getWorkPlan() != null) {
                moldNumber = sysProductRecord.getWorkPlan().getMoldNumber();
                if (moldNumber < 0) {
                    moldNumber = 1;
                }
            }
            try {
                double nowProductNum = sysProductRecord.getNowProductNum() * moldNumber;
                sysProductRecord.setTotalCount((int) nowProductNum);
                this.sysProductRecordService.updateById(sysProductRecord);
            } catch (Exception e) {

            }

        }
        return null;
    }


    @PostMapping("getDoing/{machineName}")
    public Result<?> getDoing(@PathVariable String machineName) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.eq(machineName));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.IS_NORMAL.eq(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));

        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.list(queryWrapper);
        return sysProductRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysProductRecordList);

    }

    @Autowired
    SysBomChildService sysBomChildService;
    @Autowired
    KingdeeUtils kingdeeUtils;

    @PostMapping("getDoing1/{machineName}")
    public Result<?> getDoing1(@PathVariable String machineName) throws IOException {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.eq(machineName));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.IS_NORMAL.eq(true));
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));

        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        for (SysProductRecord sysProductRecord : sysProductRecordList) {
            SysWorkPlan sysWorkPlan = sysProductRecord.getWorkPlan();
            SysBom sysBom = sysWorkPlan.getBom();
            log.error("SYSBOM:{}", sysBom);
            List<SysBomChild> sysBomChildList = this.kingdeeUtils.getPPBOMDetail(sysBom.getId());
            sysBom.setBomChildList(sysBomChildList);
            sysWorkPlan.setBom(sysBom);
            sysProductRecord.setWorkPlan(sysWorkPlan);
        }
        return sysProductRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysProductRecordList);

    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @PostMapping("list/{page}/{size}")
    public Result<?> list(@RequestBody SysProductRecord sysProductRecord, @PathVariable Integer page, @PathVariable Integer size) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        if (sysProductRecord.getProductDate() == null) {
            sysProductRecord.setProductDate(new Date());
        }
//        queryWrapper.where(SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysProductRecord.getProductDate())));
        queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("")));
        int offset = 0;
        if (page > 1) {
            offset = page * size;
        }
        queryWrapper.limit(offset, size);
        queryWrapper.orderBy(SYS_PRODUCT_RECORD.ACTUAL_START_TIME, false);
//        queryWrapper.orderBy(SYS_PRODUCT_RECORD.ACTUAL_END_TIME,true);
        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        return sysProductRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysProductRecordList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public SysProductRecord getInfo(@PathVariable Serializable id) {
        return sysProductRecordService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysProductRecord> page(Page<SysProductRecord> page) {
        return sysProductRecordService.page(page);
    }

    @PostMapping("/listByCondition")
    public Result<?> getListByCondition(@RequestBody SysProductRecord sysProductRecord) throws ParseException {
        log.error("Sys:{}", JSONObject.toJSONString(sysProductRecord));
        QueryWrapper queryWrapper = QueryWrapper.create();
        LocalDateTime localDateTime1 = LocalDateTime.now();
        LocalDate date = LocalDate.now();
        LocalDate localDate = sysProductRecord.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime localDateTime = sysProductRecord.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
//        queryWrapper.where(SYS_PRODUCT_RECORD.SHIFT.eq(sysProductRecord.getShift()));

        int hour=localDateTime1.getHour();

        if (sysProductRecord.getShift().equals("白班")) {
            if (date.equals(localDate)) {
                queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull()
                        .or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                .between(localDate.atTime(8, 10, 0), localDate.atTime(20, 10, 0))
                               ));
            } else {
             queryWrapper.where(
                        SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                .between(date.atTime(8, 10, 0), date.atTime(20, 10, 0))
                                );
            }


        } else {
            if (date.equals(localDate)) {
                log.error("A");
                if(hour>=20||hour<8){
                  queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull()
                            .or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                    .between(date.atTime(20, 0, 0), date.plusDays(1).atTime(8, 10, 0))
                            ));
                }


            } else {
                log.error("B");
                if(hour>=20||hour<8){
                 queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                            .between(date.minusDays(1).atTime(20, 0, 0),
                                    date.atTime(8, 10, 0)
                            ).or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull())
                    );
                }else{
                  queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                            .between(date.minusDays(1).atTime(20, 0, 0),
                                        date.atTime(8, 10, 0)
                            ).or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().and(SYS_PRODUCT_RECORD.EXCHANGE_TYPE.eq("小工单切换")))
                    );
                }

            }

//        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.between(localDateTime1.minusHours(12),localDateTime1)))
        }
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull());
        queryWrapper.where(SYS_PRODUCT_RECORD.MACHINE_NAME.like("A").or(SYS_PRODUCT_RECORD.MACHINE_NAME.like("B")).or(SYS_PRODUCT_RECORD.MACHINE_NAME.like("C")).or(SYS_PRODUCT_RECORD.MACHINE_NAME.like("D")));
        queryWrapper.where(SYS_PRODUCT_RECORD.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD.WORK_SHOP.eq("").or(SYS_PRODUCT_RECORD.WORK_SHOP.isNull())));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD.MACHINE_NAME, true);
        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        log.error("SQL:{}", queryWrapper.toSQL());
        List<SysProductRecord> productRecordList = new ArrayList<>();
        for (SysProductRecord productRecord : sysProductRecordList) {
            SysMachinePlc sysMachinePlc = productRecord.getSysMachinePlc();
            if (sysMachinePlc != null) {
                String lineManager = sysProductRecord.getLineManager();
                String lineManagerA = sysMachinePlc.getLineManagerA();
                String lineManagerB = sysMachinePlc.getLineManagerB();
                if (lineManagerA.contains(lineManager)) {
                    productRecord.setLineManager(lineManagerA);
                    productRecordList.add(productRecord);

                } else if (lineManagerB.contains(lineManager)) {
                    productRecord.setLineManager(lineManagerB);
                    productRecordList.add(productRecord);
                }else{
                    productRecordList.add(productRecord);
                }
            }
        }
        List<SysProductRecord> productRecords=productRecordList.stream().filter(item->item.getLineManager()!=null&&item.getLineManager().contains(sysProductRecord.getLineManager())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(productRecords)){
            productRecords=productRecordList;
        }
        return productRecords.isEmpty() ? ResultTool.fail() : ResultTool.success(productRecords);
    }
   @PostMapping("/listByConditionForScheduling")
    public Result<?> listByConditionForScheduling(@RequestBody SysProductRecord sysProductRecord) throws ParseException {
        log.error("Sys:{}", JSONObject.toJSONString(sysProductRecord));
        QueryWrapper queryWrapper = QueryWrapper.create();
        LocalDateTime localDateTime1 = LocalDateTime.now();
        LocalDate date = LocalDate.now();
        LocalDate localDate = sysProductRecord.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime localDateTime = sysProductRecord.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
//        queryWrapper.where(SYS_PRODUCT_RECORD.SHIFT.eq(sysProductRecord.getShift()));


        if (sysProductRecord.getShift().equals("白班")) {
            if (date.equals(localDate)) {
                log.error("A");

                queryWrapper.where(SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(localDate)
                        .or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                .between(localDate.atTime(8, 10, 0), localDate.atTime(20, 10, 0))
                               ).or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().and(SYS_PRODUCT_RECORD.PRODUCT_DATE.le(localDate))));
            } else if(date.isBefore(localDate)) {
                log.error("B");

                queryWrapper.where(
                        SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(localDate)
                               .or(
                        SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                .between(date.atTime(8, 10, 0), date.atTime(20, 10, 0))
                                ).or(SYS_PRODUCT_RECORD.EXCHANGE_TYPE.eq("小工单切换").and(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull())));
            }else{
                queryWrapper.where(
                        SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(localDate)
                                .or(
                                        SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                                .between(date.atTime(8, 10, 0), date.atTime(20, 10, 0))
                                ).or(SYS_PRODUCT_RECORD.EXCHANGE_TYPE.eq("小工单切换").and(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull())));
            }


        } else {
            if (date.equals(localDate)) {
                log.error("A");
                queryWrapper.where
                        (SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(localDate)
                                .or(
                                        SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().and(SYS_PRODUCT_RECORD.PRODUCT_DATE.le(localDate))
                                ).or(
                                        SYS_PRODUCT_RECORD.ACTUAL_END_TIME.between(
                                                localDate.atTime(20, 0, 0),
                                                localDate.plusDays(1).atTime(8, 10, 0))
                        ));

            } else if(date.isBefore(localDate)) {
                log.error("B");
                queryWrapper.where((SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNotNull().and(SYS_PRODUCT_RECORD.PRODUCT_DATE.le(localDate))).or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME
                                .between(date.minusDays(1).atTime(20, 0, 0), date.atTime(8, 10, 0))
                        )
                );
            }else{
                queryWrapper.where(SYS_PRODUCT_RECORD.PRODUCT_DATE.eq(localDate).or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().and(SYS_PRODUCT_RECORD.PRODUCT_DATE.le(localDate)))
                        .or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.between(localDate.atTime(20, 0, 0), localDate.plusDays(1).atTime(8, 10, 0))
                        ));

            }

//        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull().or(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.between(localDateTime1.minusHours(12),localDateTime1)))
        }
        ;
        queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull());
        queryWrapper.groupBy(SYS_PRODUCT_RECORD.MACHINE_NAME,SYS_PRODUCT_RECORD.WORK_PLAN_ID);
        queryWrapper.orderBy(SYS_PRODUCT_RECORD.MACHINE_NAME, true);
        RelationManager.addIgnoreRelations("productRecordList");/**/
        RelationManager.addIgnoreRelations("bom");/**/
        RelationManager.addIgnoreRelations("workPlan");/**/
        RelationManager.addIgnoreRelations("productInfo");/**/
//       RelationManager.addIgnoreRelations("sysMachinePlc");
        List<SysProductRecord> sysProductRecordList = this.sysProductRecordService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        log.error("SQL:{}", queryWrapper.toSQL());
        List<SysProductRecord> productRecordList = new ArrayList<>();
        for (SysProductRecord productRecord : sysProductRecordList) {
            SysMachinePlc sysMachinePlc = productRecord.getSysMachinePlc();
            if (sysMachinePlc != null) {
                String lineManager = sysProductRecord.getLineManager();
                String lineManagerA = sysMachinePlc.getLineManagerA();
                String lineManagerB = sysMachinePlc.getLineManagerB();
                if (lineManagerA.contains(lineManager)) {
                    productRecord.setLineManager(lineManagerA);
                    productRecordList.add(productRecord);
                } else if (lineManagerB.contains(lineManager)) {
                    productRecord.setLineManager(lineManagerB);
                    productRecordList.add(productRecord);

                }
            }
//            productRecord.setSysMachinePlc(null);
//            productRecord.setSysPlc(null);
        }

//        return sysProductRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysProductRecordList);
        return productRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(productRecordList);
    }

    @Autowired
    SysProductRecordShiftService sysProductRecordShiftService;

    public void saveProductNight(SysProductRecord sysProductRecord) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        SysProductRecordShift nightShiftProduct = JSONObject.parseObject(JSONObject.toJSONString(sysProductRecord), SysProductRecordShift.class);
        LocalDateTime localDateTime = LocalDateTime.now();
        if (localDateTime.getHour() < 8) {
            localDateTime = localDateTime.minusDays(1);
        }
        LocalDate productDate = localDateTime.toLocalDate();
        nightShiftProduct.setShift("夜班");
        nightShiftProduct.setId(UUID.randomUUID().toString() + "-lightShift");
        nightShiftProduct.setActualEndTime(new Date());
        nightShiftProduct.setEntry(false);
        nightShiftProduct.setProductRecordId(sysProductRecord.getId());
        LocalDateTime start = sysProductRecord.getActualStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_PLAN_ID.eq(nightShiftProduct.getWorkPlanId()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(nightShiftProduct.getShift()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(productDate));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("")));

        queryWrapper.limit(1);
        SysProductRecordShift oldProductRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
        boolean isAdd = true;
        if (oldProductRecordShift != null) {
            nightShiftProduct.setId(oldProductRecordShift.getId());
            isAdd = false;
        }

        LocalDate yesterday = productDate.minusDays(1);
        queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.eq(sysProductRecord.getProductId()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(productDate.minusDays(1)));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.IS_ENTRY.eq(false));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq("夜班"));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("")));

        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.ACTUAL_START_TIME, true);
        queryWrapper.limit(1);
        SysProductRecordShift productRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
        if (productRecordShift != null) {
            log.error("有尾箱");
            nightShiftProduct.setLastTailBoxCount(productRecordShift.getNowTailBoxCount());
        } else {
            log.error("没有尾箱");
            nightShiftProduct.setLastTailBoxCount(0);
        }

        nightShiftProduct.setProductDate(Date.from(productDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
//        LocalDateTime yesterday1=localDateTime.minusDays(1);
        LocalDateTime startTarget = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 20, 0, 0);
        LocalDateTime end = LocalDateTime.now();


        if (start.isBefore(startTarget)) {
            log.error("之后");

            if (isAdd) {
                int total = this.getTotalCount(sysProductRecord, startTarget, end);
                nightShiftProduct.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, startTarget, end);
                nightShiftProduct.setBadNum(bad);
                nightShiftProduct.setGoodNum(total - bad);
                nightShiftProduct.setActualStartTime(Date.from(startTarget.atZone(ZoneId.systemDefault()).toInstant()));
                nightShiftProduct.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            } else {
                int total = this.getTotalCount(sysProductRecord, startTarget, end) + oldProductRecordShift.getTotalCount();
                nightShiftProduct.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, startTarget, end) + oldProductRecordShift.getBadNum();
                nightShiftProduct.setBadNum(bad);
                nightShiftProduct.setGoodNum(total - bad);
                nightShiftProduct.setActualStartTime(oldProductRecordShift.getActualStartTime());
                nightShiftProduct.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            }


        } else {
            log.error("之前");

            if (isAdd) {
                int total = this.getTotalCount(sysProductRecord, start, end);
                nightShiftProduct.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, start, end);
                nightShiftProduct.setBadNum(bad);
                nightShiftProduct.setGoodNum(total - bad);
                nightShiftProduct.setActualStartTime(Date.from(startTarget.atZone(ZoneId.systemDefault()).toInstant()));
                nightShiftProduct.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            } else {
                int total = this.getTotalCount(sysProductRecord, start, end) + oldProductRecordShift.getTotalCount();
                nightShiftProduct.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, start, end) + oldProductRecordShift.getBadNum();
                nightShiftProduct.setBadNum(bad);
                nightShiftProduct.setGoodNum(total - bad);
                nightShiftProduct.setActualStartTime(oldProductRecordShift.getActualStartTime());
                nightShiftProduct.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            }
        }

        try {

            if (isAdd) {
                boolean result = this.sysProductRecordShiftService.save(nightShiftProduct);
            } else {
                boolean result = this.sysProductRecordShiftService.updateById(nightShiftProduct);
            }

        } catch (Exception e) {

        }

    }

    public int getTotalCount(SysProductRecord sysProductRecord, LocalDateTime start, LocalDateTime end) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PLC.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PLC.CREATE_TIME.between(start, end));
        queryWrapper.select(max(SYS_PLC.MODE_NUM).subtract(min(SYS_PLC.MODE_NUM)).as("mode_num"))
                .select(SYS_PLC.ID, SYS_PLC.CREATE_TIME, SYS_PLC.MACHINE_NAME);
        log.error("SQL:{}", queryWrapper.toSQL());
        SysPlc sysPlc = this.sysPlcService.getOne(queryWrapper);
        try{
            if (sysPlc != null) {
                return (int) ((int) sysPlc.getModeNum() * sysProductRecord.getWorkPlan().getMoldNumber());
            } else {
                return 0;
            }
        }catch (Exception e){
            return 0;
        }

    }

    public int getBadCount(SysProductRecord sysProductRecord, LocalDateTime start, LocalDateTime end) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysProductRecord.getWorkPlanId()));
        queryWrapper.where(SYS_BAD_RECORD.CREATE_TIME.between(start, end));
        queryWrapper.select(sum(SYS_BAD_RECORD.NUM).as("num"));
        SysBadRecord badRecord = this.sysBadRecordService.getOne(queryWrapper);
        if (badRecord != null) {
            return (int) badRecord.getNum();
        } else {
            return 0;
        }
    }

    public void saveProductLight(SysProductRecord sysProductRecord) throws IOException {
        LocalDate productDate = LocalDate.now();
        ObjectMapper objectMapper = new ObjectMapper();
        SysProductRecordShift sysProductRecordShift = JSONObject.parseObject(JSONObject.toJSONString(sysProductRecord), SysProductRecordShift.class);
        QueryWrapper queryWrapper = QueryWrapper.create();
        sysProductRecordShift.setShift("白班");
        sysProductRecordShift.setActualEndTime(new Date());
        sysProductRecordShift.setEntry(false);
        sysProductRecordShift.setId(UUID.randomUUID().toString());
        sysProductRecordShift.setProductRecordId(sysProductRecord.getId());
        Date actualStartTime=sysProductRecord.getActualStartTime();
        queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_PLAN_ID.eq(sysProductRecordShift.getWorkPlanId()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysProductRecordShift.getShift()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(productDate));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("")));

        queryWrapper.limit(1);
        SysProductRecordShift oldProductRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
        log.error("OldProduct:{}",JSONObject.toJSONString(oldProductRecordShift));
        boolean isAdd = true;
        if (oldProductRecordShift != null) {
            sysProductRecordShift.setId(oldProductRecordShift.getId());
            isAdd = false;
        }

        LocalDateTime start = sysProductRecord.getActualStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDate startDate = start.toLocalDate();
        LocalDate localDateTime = LocalDate.now();
        LocalDateTime startTarget = localDateTime.atTime(8, 0, 0);
        LocalDate startTargetDate = startTarget.toLocalDate();
        LocalDateTime end = LocalDateTime.now();

        if (start.isBefore(startTarget)) {
            log.error("之后");

            if (isAdd) {
                int total = this.getTotalCount(sysProductRecord, startTarget, end);
                sysProductRecordShift.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, startTarget, end);
                sysProductRecordShift.setBadNum(bad);
                sysProductRecordShift.setGoodNum(total - bad);
                sysProductRecordShift.setActualStartTime(Date.from(startTarget.atZone(ZoneId.systemDefault()).toInstant()));
                sysProductRecordShift.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            } else {
                int total = this.getTotalCount(sysProductRecord, startTarget, end) + oldProductRecordShift.getTotalCount();
                sysProductRecordShift.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, startTarget, end) + oldProductRecordShift.getBadNum();
                sysProductRecordShift.setBadNum(bad);
                sysProductRecordShift.setGoodNum(total - bad);
                sysProductRecordShift.setActualStartTime(oldProductRecordShift.getActualStartTime());
                sysProductRecordShift.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            }


        } else {
            log.error("之前");

            if (isAdd) {
                int total = this.getTotalCount(sysProductRecord, start, end);
                sysProductRecordShift.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, start, end);
                sysProductRecordShift.setBadNum(bad);
                sysProductRecordShift.setGoodNum(total - bad);
                sysProductRecordShift.setActualStartTime(Date.from(startTarget.atZone(ZoneId.systemDefault()).toInstant()));
                sysProductRecordShift.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            } else {
                int total = this.getTotalCount(sysProductRecord, start, end) + oldProductRecordShift.getTotalCount();
                sysProductRecordShift.setTotalCount(total);
                int bad = this.getBadCount(sysProductRecord, start, end) + oldProductRecordShift.getBadNum();
                sysProductRecordShift.setBadNum(bad);
                sysProductRecordShift.setGoodNum(total - bad);
                sysProductRecordShift.setActualStartTime(oldProductRecordShift.getActualStartTime());
                sysProductRecordShift.setActualEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            }
        }

        queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(sysProductRecord.getMachineName()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_ID.eq(sysProductRecord.getProductId()));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(productDate.minusDays(1)));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.IS_ENTRY.eq(false));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq("白班"));
        queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("成型车间").or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.isNull()).or(SYS_PRODUCT_RECORD_SHIFT.WORK_SHOP.eq("")));
        queryWrapper.orderBy(SYS_PRODUCT_RECORD_SHIFT.ACTUAL_END_TIME, true);
        queryWrapper.limit(1);
        SysProductRecordShift productRecordShift = this.sysProductRecordShiftService.getOne(queryWrapper);
        if (productRecordShift != null) {
            sysProductRecordShift.setLastTailBoxCount(productRecordShift.getNowTailBoxCount());
        } else {
            sysProductRecordShift.setLastTailBoxCount(0);
        }
        sysProductRecordShift.setProductDate(Date.from(productDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        if (sysProductRecord.getWorkPlan() != null) {
            sysProductRecordShift.setQuantity(sysProductRecord.getWorkPlan().getQuantity());
        } else {
            sysProductRecordShift.setQuantity(1);
        }

        if (isAdd) {
            boolean result = this.sysProductRecordShiftService.save(sysProductRecordShift);
        } else {
            boolean result = this.sysProductRecordShiftService.updateById(sysProductRecordShift);

        }
    }

}
